/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.citi.dahg.cve;

import com.citi.dahg.cve.controller.exceptions.SystemException;
import com.citi.dahg.cve.controller.service.local.RecursoService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.apache.commons.io.IOUtils;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author dh90940
 */
@ManagedBean
@ViewScoped
public class FileUploadBean extends BasicManagedBean {
    
    @EJB
    private RecursoService recursoService;
    
    public void handleFileUpload(FileUploadEvent event) {
        List<String> errores = new ArrayList<String>();
        List<String> lineas=null;
        try {
            lineas = IOUtils.readLines(event.getFile().getInputstream());
            int fila=1;
            for(String linea:lineas) {
                try {
                    recursoService.createRecursoFromFile(fila, linea);
                } catch (SystemException ex) {
                    errores.add("fila"+fila+" - "+ex.getMessage());
                }
                fila++;
            }
        } catch (IOException ex) {
            addError(ex.getMessage());
        }
        
        if(errores.size()==0) addInfo("Archivo cargado exitosamente");
        else {            
            int exitosos = lineas.size() - errores.size();
            addInfo(exitosos+" registros cargados satisfactoriamente");
            if(errores.size()>5)
                addError("Error en "+errores.size()+" filas");
            else {
                for(String error:errores)
                    addError(error);
            }           
            
        }
        
    }    
    
}
